<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <title>Document</title>
</head>

<body>
    <form id="sendForm">
        <input id="sendText" placeholder="Text to send">
    </form>
    <pre id="incomming">test</pre>
</body>

<script type="text/javascript">
    var start = function () {
        var inc = document.getElementById('incomming');
        var wsImpl = window.WebSocket || window.MozWebSocket;
        var form = document.getElementById('sendForm');
        var input = document.getElementById('sendText');
        inc.innerHTML += "connecting to server ..<br/>";
        // 创建新的websocket新连接端口为7181
        window.ws = new wsImpl('ws://localhost:7181/');
        // 当数据从服务器服务中心发送后，继续向下运行过程
        ws.onmessage = function (evt) {
            inc.innerHTML += evt.data + '<br/>';
        };
        // 当链接对象找到服务端成功对接后，提示正常打开
        ws.onopen = function () {
            inc.innerHTML += '.. connection open<br/>';
        };
        // 当链接对象未找找到服务端成功对接后，提示打开失败，别切单项关闭
        ws.onclose = function () {
            inc.innerHTML += '.. connection closed<br/>';
        }
        form.addEventListener('submit', function (e) {
            e.preventDefault();
            var val = input.value;
            ws.send(val);
            input.value = "";
        });
    }
    window.onload = start();
</script>
</html>